package org.ikross.twitter.connector;

import java.io.InputStream;
import java.security.KeyStore;
import java.util.Set;

import org.ikross.twitter.connector.parameter.IParameter;
import org.ikross.twitter.connector.parameter.POSTParameter;
import org.ikross.twitter.exception.ConnectorException;

public class AuthenticationConnector extends Connector {
	
	private IConnector task;
	private String username;
	private KeyStore.PasswordProtection password;
	
	public AuthenticationConnector(IConnector task, String username, KeyStore.PasswordProtection password){
		if(task == null || username == null || password == null)
			throw new IllegalArgumentException("Arguments must not be null");
		
		this.task = task;
		char[] pass = password.getPassword();
		IParameter parameter = new POSTParameter("Authorization", "Basic " + new sun.misc.BASE64Encoder().encode((username + ":" + String.valueOf(pass)).getBytes()));
		for (int i = 0; i < pass.length; i++) {
			pass[i]=0;
		}
		pass=null;
		this.addParameter(parameter.getKey(), parameter);
		
		this.username=username;
		this.password=password;
	}

	@Override
	public void addParameter(String key, IParameter value) {
		this.task.addParameter(key, value);
	}

	@Override
	public Set<String> getKeyParameters() {
		return this.task.getKeyParameters();
	}

	@Override
	public IParameter getParameter(String key) {
		return this.task.getParameter(key);
	}

	@Override
	public boolean checkParameters() {
		return this.task.checkParameters();
	}

	@Override
	public InputStream execute() throws ConnectorException {
		return this.task.execute();
	}

	public IConnector clone() {
		return new AuthenticationConnector(this.task.clone(), new String(this.username.toCharArray()), new KeyStore.PasswordProtection(this.password.getPassword()));
	}
}